﻿using System;
using System.Linq;
using System.Data;
using GSSoftSL.Web.Models;
using Microsoft.Reporting.WebForms;

namespace GSSoftSL.Web
{
    public partial class Report : System.Web.UI.Page
    {
        private bool _inLai = false;
        private EnumReport _type = EnumReport.BienLaiHocPhi;
        protected void Page_Load(object sender, EventArgs e)
        {
            int tmp;
            if (Request.QueryString["type"] == null || !int.TryParse(Request.QueryString["type"], out tmp))
                return;
            if (!Page.IsPostBack)
            {
                _type = (EnumReport) tmp;
                if (_type == EnumReport.BienLaiHocPhi)
                {
                    if (Request.QueryString["id"] == null || Request.QueryString["id"].Length != 36)
                        return;
                    InBienLai(new Guid(Request.QueryString["id"]));
                }
                
                //ShowReportViewer();
                //ReportViewer1.LocalReport.ReportPath = Server.MapPath("~/Reports/Report1.rdlc");
                //ReportViewer1.LocalReport.Refresh();
            }

            //InBienLai(new Guid("9671515B-B1B6-4988-9360-9DCE69B17915"));
            //ShowReportViewer();
            /*if (Request.QueryString["ShowReportViewer"] == "False")
            {
                RenderReport();
            }
            else
            {
                if (!Page.IsPostBack)
                {
                    ShowReportViewer();
                }
            }*/
        }

        #region LoadData
        private DataTable LoadData()
        {
            

            return null;
        }
        #endregion

        #region RenderReport
        private void RenderReport()
        {
            // CheckBox to see if there is any data
            if (LoadData().Rows.Count > 0)
            {
                LocalReport localReport = new LocalReport();
                localReport.ReportPath = Server.MapPath("~/Report1.rdlc");

                ReportDataSource reportDataSource = new ReportDataSource("DataSet1", LoadData());
                localReport.DataSources.Add(reportDataSource);

                string reportType = "pdf";
                string mimeType = "application/pdf";
                string encoding;
                string fileNameExtension;

                //The DeviceInfo settings should be changed based on the reportType
                //http://msdn2.microsoft.com/en-us/library/ms155397.aspx
                string deviceInfo =
                "<DeviceInfo>" +
                " <OutputFormat>PDF</OutputFormat>" +
                " <PageWidth>8.5in</PageWidth>" +
                " <PageHeight>11in</PageHeight>" +
                " <MarginTop>0.5in</MarginTop>" +
                " <MarginLeft>1in</MarginLeft>" +
                " <MarginRight>1in</MarginRight>" +
                " <MarginBottom>0.5in</MarginBottom>" +
                "</DeviceInfo>";

                Warning[] warnings;
                string[] streams;
                byte[] renderedBytes;

                //Render the report
                renderedBytes = localReport.Render(
                reportType,
               deviceInfo,
               out mimeType,
               out encoding,
               out fileNameExtension,
               out streams,
               out warnings);

                //Clear the response stream and write the bytes to the outputstream
                //Set content-disposition to "attachment" so that user is prompted to take an action
                //on the file (open or save)
                Response.Clear();
                Response.ContentType = mimeType;
                //Response.AddHeader("content-disposition", "attachment; filename=foo." + fileNameExtension);
                Response.BinaryWrite(renderedBytes);
                Response.End();
            }
            else
            {
                // There were no records returned
                Response.Clear();
                //Response.AddHeader("content-disposition", "attachment; filename=foo." + fileNameExtension);
                Response.Write("No Data");
                Response.End();
            }
        }
        #endregion

        #region ShowReportViewer
        private void ShowReportViewer()
        {
            this.ReportViewer1.ProcessingMode = ProcessingMode.Local;
            this.ReportViewer1.LocalReport.ReportPath = Server.MapPath("~/Report1.rdlc");
            ReportViewer1.LocalReport.DataSources.Add(
               new ReportDataSource("DataSet1", LoadData()));
        }
        #endregion

        public void InBienLai(Guid BienLaiId)
        {
            try
            {


                BienLai bienLai = new BienLai();
                GSSoftSLEntities dc = new GSSoftSLEntities();
                //using (GSSoftSLEntities dc = new GSSoftSLEntities())
                //{
                //dc.BienLais.First().BienLaiCTs.First().KhoaHoc.Lop.Mon
                bienLai = dc.BienLais.Include("BienLaiCTs").Include("BienLaiCTs.KhoaHoc").Include(
                    "BienLaiCTs.KhoaHoc.Lop").
                    Include("BienLaiCTs.KhoaHoc.Lop.Mon").Single(n => n.BienLaiId == BienLaiId);
                //}
                string StrLop, StrMon;
                StrLop = String.Join(", ", bienLai.BienLaiCTs.Select(n => n.KhoaHoc.Lop.TenLop).ToArray());
                StrMon = String.Join(", ", bienLai.BienLaiCTs.Select(n => n.KhoaHoc.Lop.Mon.TenMon).Distinct().ToArray());
                HocVien hv = bienLai.HocVien;

                string HoTen = this.Context.Profile["HoTen"].ToString();
                ReportParameter paraSoBienLai = new ReportParameter("SoBienLai", bienLai.SoBienLai);
                ReportParameter paraHocVien = new ReportParameter("NguoiDong", hv.HoLot + " " + hv.Ten);
                ReportParameter paraTongTien = new ReportParameter("TongTien", bienLai.TongTienSauGiam.ToString("N2"));
                ReportParameter paraTienChu = new ReportParameter("TienChu",
                                                                  Utility.DocTienBangChu(
                                                                      (long) bienLai.TongTienSauGiam, " đồng chẵn"));
                ReportParameter paraGhiChu = new ReportParameter("GhiChu", bienLai.GhiChu);
                ReportParameter paraNgayThu =
                    new ReportParameter("NgayThu", string.Format("Ngày {0} tháng {1} năm {2}",
                                                                 bienLai.NgayDong.Day.ToString().PadLeft(2, '0'),
                                                                 bienLai.NgayDong.Month.ToString().PadLeft(2, '0'),
                                                                 bienLai.NgayDong.Year));
                ReportParameter paraNguoiThu = new ReportParameter("NguoiThu", HoTen);
                ReportParameter paraInLai = new ReportParameter("InLai", _inLai.ToString());
                ReportParameter paraMaHV = new ReportParameter("MaHV", hv.MaHV);
                ReportParameter paraDiaChi = new ReportParameter("DiaChi", hv.DiaChiNha);
                ReportParameter paraDienThoai = new ReportParameter("DienThoai", hv.DTCaNhan);
                ReportParameter paraLop = new ReportParameter("Lop", StrLop);
                ReportParameter paraMon = new ReportParameter("Mon", StrMon);
                ReportParameter paraKhoaHoc;
                if (bienLai.BienLaiCTs.Count == 1)
                    paraKhoaHoc = new ReportParameter("KhoaHoc", bienLai.BienLaiCTs.First().KhoaHoc.TenKhoaHoc);
                else
                    paraKhoaHoc = new ReportParameter("KhoaHoc", "");

                /*bool logoExist = true;
                string logoPath = Path.Combine(Application.StartupPath, "logo.png");
                if (!File.Exists(logoPath))
                {
                    logoPath = Path.Combine(Application.StartupPath, "logo.jpg");
                    if (!File.Exists(logoPath))
                    {
                        logoPath = Path.Combine(Application.StartupPath, "logo.bmp");
                        if (!File.Exists(logoPath))
                        {
                            logoExist = false;
                        }
                    }
                }
                ReportParameter paraPath;
                if (logoExist)
                    paraPath = new ReportParameter("Path", "file:///" + logoPath);
                else
                    paraPath = new ReportParameter("Path", "");*/
                ReportParameter paraPath = new ReportParameter("Path", "");
                ReportViewer1.ProcessingMode = ProcessingMode.Local;
                //ReportViewer1.LocalReport.ReportPath = Server.MapPath("~/Reports/Report1.rdlc");
                ReportViewer1.LocalReport.ReportPath = Server.MapPath("~/Reports/RptBienLai.rdlc");
                ReportViewer1.LocalReport.EnableExternalImages = true;
                //Application.StartupPath + @"\BaoBieu\Report\RptBienLai.rdlc";
                ReportViewer1.LocalReport.EnableExternalImages = true;
                //ReportViewer1.LocalReport.SetParameters(new ReportParameter("title", "test"));
                ReportViewer1.LocalReport.SetParameters(new ReportParameter[]
                                                            {
                                                                paraSoBienLai,
                                                                paraHocVien,
                                                                paraTongTien,
                                                                paraTienChu,
                                                                paraGhiChu,
                                                                paraNgayThu,
                                                                paraNguoiThu,
                                                                paraInLai,
                                                                paraMaHV,
                                                                paraDiaChi,
                                                                paraDienThoai,
                                                                paraLop,
                                                                paraMon,
                                                                paraKhoaHoc,
                                                                paraPath
                                                            });
                ReportViewer1.LocalReport.Refresh();
            }
            catch (Exception er)
            {
                
            }
        }

        /*public void InitInDanhSachLop(Lop lop, int reportType)
        {
            List<HocVien> list = lop.LopHocViens.Select(n => n.HocVien).OrderBy(n => n.MaHV).OrderBy(n => n.HoLot).OrderBy(n => n.Ten).ToList();
            /*var query = from LopHocVien hv in _lop.LopHocViens
                        let n = hv.HocVien
                        sel#1#
            ReportParameter paraNguoiThu = new ReportParameter("Caption", "Danh sach học viên lớp " + lop.TenLop);
            //reportViewer1.LocalReport.ReportPath = Path.Combine(Application.StartupPath, @"\BaoBieu\Report\RptDSLop.rdlc");
            if (reportType == 0)
                ReportViewer1.LocalReport.ReportPath = Application.StartupPath + @"\BaoBieu\Report\RptDSLop.rdlc";
            else
                ReportViewer1.LocalReport.ReportPath = Application.StartupPath + @"\BaoBieu\Report\RptDSLopChiTiet.rdlc";
            ReportViewer1.LocalReport.SetParameters(new ReportParameter[]
                                                        {
                                                            paraNguoiThu
                                                        });
            ReportDataSource rds = new ReportDataSource("DSHocVien", list);
            ReportViewer1.LocalReport.DataSources.Clear();
            ReportViewer1.LocalReport.DataSources.Add(rds);
        }*/

        /*public void InitInDanhSachHocSinhLop(Guid[] lstKhoaHoc)
        {
            string sqlWhere = "WHERE KhoaHocId IN (";
            if (lstKhoaHoc.Length == 1)
                sqlWhere += "'" + lstKhoaHoc[0] + "') ";
            else
            {
                int i;
                for (i = 0; i < lstKhoaHoc.Length - 1; i++)
                    sqlWhere += "'" + lstKhoaHoc[i] + "', ";
                sqlWhere += "'" + lstKhoaHoc[i] + "') ";
            }
            string sql =
                string.Format(
                    @"  SELECT	hv.MaHV, hv.HoLot, hv.Ten, hv.GioiTinh, hv.HoTenCha, hv.DTCha AS DienThoaiCha, hv.HoTenMe, hv.DTMe AS DienThoaiMe, 
		                        t.TenLop, t.TenKhoaHoc, t.DaDong AS DaDongHocPhi, t.TenMon, t.MaKhoaHoc
                        FROM HocVien hv INNER JOIN
                        (
	                        SELECT	lhv.MaHV, l.MaLop, l.TenLop, l.MaMon, kh.TenKhoaHoc, m.TenMon, kh.MaKhoaHoc,
			                        CASE WHEN khct.MaHV IS NULL THEN 0
				                         ELSE 1
			                        END AS DaDong
	                        FROM
	                        (SELECT LopId, KhoaHocId, TenKhoaHoc, MaKhoaHoc FROM KhoaHoc {0}) AS kh
	                        INNER JOIN LopHocVien lhv ON kh.LopId = lhv.LopId
	                        INNER JOIN Lop l ON l.LopId = kh.LopId
                            INNER JOIN Mon m on l.MaMon = m.MaMon
	                        LEFT JOIN KhoaHocChiTiet khct ON khct.MaHV = lhv.MaHV
                        ) AS t ON hv.MaHV = t.MaHV
                        ORDER BY t.MaLop, t.MaKhoaHoc, hv.Ten, hv.HoLot", sqlWhere);
            EduDataProvider edp = new EduDataProvider(StaticGS.ConnectionString);
            DataTable dt = edp.GetDataTable(sql, CommandType.Text);
            ReportViewer1.LocalReport.ReportPath = Application.StartupPath + @"\BaoBieu\Report\RptDSHocSinhLop.rdlc";
            ReportDataSource rds = new ReportDataSource("DanhSachHVLop", dt);
            ReportViewer1.LocalReport.DataSources.Clear();
            ReportViewer1.LocalReport.DataSources.Add(rds);
        }*/
    }
}